package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Mqtt的消息中间件 EMQX 客户端配置
 */
@Configuration
public class MqttConfiguration {

    /**
     * 用户名  这些配置类的消息应该放到配置文件或者nacos中（nacos提供了服务注册和配置管理）
     */
    private String userName = "admin";

    /**
     * 密码
     */
    private String password = "public";

    /**
     * 连接地址 tcp协议 端口 1883
     */
    private static final String BROKER_URL = "tcp://127.0.0.1:1883";

    private static final String CLIENT_ID = "order_service_client";

    @Autowired
    private MqttContext mqttContext;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        //通过连接地址和客户端id和emqx进行连接
        //客户端id  目的是要告诉我们的服务器 谁在连接他
        MqttClient mqttClient = new MqttClient(BROKER_URL,CLIENT_ID);
        //连接相关的配置
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        //设置用户名
        mqttConnectOptions.setUserName(userName);
        //设置密码
        mqttConnectOptions.setPassword(password.toCharArray());
        //自动重连
        mqttConnectOptions.setAutomaticReconnect(true);
        //设置版本号
        mqttConnectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        //清理会话session
        mqttConnectOptions.setCleanSession(true);
        //设置mqtt回调类MqttConsumer
        mqttClient.setCallback(new MqttConsumer(mqttContext,mqttClient));
        //基于上面设置的mqttConnectOptions进行连接 和emqx
        mqttClient.connect(mqttConnectOptions);

        return mqttClient;

    }
}
